package com.jinlejia.feedback.idea.ui;

import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.freedom.yefeng.yfrecyclerview.YfListInterface;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.jinlejia.erp.utils.DbUtil;
import com.jinlejia.feedback.R;
import com.jinlejia.feedback.common.RecycleViewDivider;
import com.jinlejia.feedback.common.databinding.CommonEvent;
import com.jinlejia.feedback.databinding.FbActivitySearchBinding;
import com.jinlejia.feedback.idea.ui.adapter.FbSearchHistoryAdapter;
import com.jinlejia.feedback.idea.ui.base.FbBaseActivity;
import com.jinlejia.feedback.idea.ui.bean.FbSearchQuestionHistoryBean;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.assit.WhereBuilder;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @author SongJiaTai
 * @description:搜索页面
 * @date :2019/6/28 15:31
 */
public class FbsearchActivity extends FbBaseActivity {
    FbSearchHistoryAdapter historyAdapter;

    private FbActivitySearchBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding  = DataBindingUtil.setContentView(this, R.layout.fb_activity_search);
        binding.setCommonEvent(CommonEvent.obtain());
        binding.setEvent(this);
        initvVew();
    }

    private void initvVew() {
        binding.yfrvSearchResult.setHasFixedSize(true);
        binding.yfrvSearchResult.setLayoutManager(new LinearLayoutManager(this));
        binding.yfrvSearchResult.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.fb_ItemDecoration)));

        //搜索历史
        ArrayList<FbSearchQuestionHistoryBean> historyList = new ArrayList<>();
        historyList.addAll(DbUtil.getDB(this).single().query(FbSearchQuestionHistoryBean.class));
        binding.etSearchText.setHint("请输入问题进行搜索");
        Collections.reverse(historyList);
        historyAdapter = new FbSearchHistoryAdapter(historyList);
        if (historyList.size() > 0)
            historyAdapter.addFooter("清空历史");
        binding.yfrvSearchResult.setAdapter(historyAdapter);
        historyAdapter.setOnFooterViewClickListener(new YfListInterface.OnFooterViewClickListener() {
            @Override
            public void onFooterViewClick(View view, Object o) {

                FbDeleteDialog dialog = new FbDeleteDialog(FbsearchActivity.this, "清空历史", "确定清空历史记录?");
                dialog.show();
                dialog.setConfirmListener(new FbDeleteDialog.OnConfirmListener() {
                    @Override
                    public void confirm() {
                        DbUtil.getDB(FbsearchActivity.this).single().deleteAll(FbSearchQuestionHistoryBean.class);
                        historyAdapter.getData().clear();
                        historyAdapter.changeMode(YfListMode.MODE_EMPTY);
                    }
                });
            }
        });


        historyAdapter.setOnItemClickListener(new YfListInterface.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object o) {
                if (o instanceof FbSearchQuestionHistoryBean) {
                    String name = ((FbSearchQuestionHistoryBean) o).getName();
                    Intent data = new Intent();
                    data.putExtra("data", name);
                    setResult(RESULT_OK, data);
                }
                finish();
            }
        });


        binding.etSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(binding.etSearchText.getText().toString())) {
                        String name = binding.etSearchText.getText().toString();
                        Intent data = new Intent();
                        data.putExtra("data", name);
                        setResult(RESULT_OK, data);

                        FbSearchQuestionHistoryBean rshb = new FbSearchQuestionHistoryBean(name);
                        ArrayList<FbSearchQuestionHistoryBean> shbList = DbUtil.getDB(FbsearchActivity.this).single().query(FbSearchQuestionHistoryBean.class);

                        if (shbList.size() == 10) {
                            //数量达到10，删除第一个
                            DbUtil.getDB(FbsearchActivity.this).single().delete(shbList.get(0));
                        }
                        if (DbUtil.getDB(FbsearchActivity.this).single().query(new QueryBuilder<>(FbSearchQuestionHistoryBean.class).whereEquals("name", rshb.getName())).size() == 0) {
                            //不包含，直接存
                            DbUtil.getDB(FbsearchActivity.this).single().save(rshb);
                        } else {
                            //已经存在，先删除再存
                            DbUtil.getDB(FbsearchActivity.this).single().delete(WhereBuilder.create(FbSearchQuestionHistoryBean.class, "name=?", new String[]{rshb.getName()}));
                            DbUtil.getDB(FbsearchActivity.this).single().save(rshb);
                        }
                    }else{
                        setResult(RESULT_CANCELED);
                    }
                    finish();
                    return true;
                }
                return false;

            }
        });


        binding.etSearchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    binding.btClear.setVisibility(View.VISIBLE);
                } else {
                    binding.btClear.setVisibility(View.INVISIBLE);
                }
            }
        });

    }


    public void tvSearchOnclick(View view){
        if (!TextUtils.isEmpty(binding.etSearchText.getText().toString())){
            String name = binding.etSearchText.getText().toString();
            Intent data = new Intent();
            data.putExtra("data", name);
            setResult(RESULT_OK, data);


            FbSearchQuestionHistoryBean rshb = new FbSearchQuestionHistoryBean(name);
            ArrayList<FbSearchQuestionHistoryBean> shbList = DbUtil.getDB(this).single().query(FbSearchQuestionHistoryBean.class);


            if (shbList.size() == 10) {
                //数量达到10，删除第一个
                DbUtil.getDB(this).single().delete(shbList.get(0));
            }
            if (DbUtil.getDB(this).single().query(new QueryBuilder<>(FbSearchQuestionHistoryBean.class).whereEquals("name", rshb.getName())).size() == 0) {
                //不包含，直接存
                DbUtil.getDB(this).single().save(rshb);
            } else {
                //已经存在，先删除再存
                DbUtil.getDB(this).single().delete(WhereBuilder.create(FbSearchQuestionHistoryBean.class, "name=?", new String[]{rshb.getName()}));
                DbUtil.getDB(this).single().save(rshb);
            }
        }else{
            setResult(RESULT_CANCELED);
        }
        finish();
    }


    public void clearOnclick(View view){
        binding.etSearchText.setText("");
    }
}
